package com.ruoyi.common.utils.wrapper;

import com.alibaba.fastjson.JSON;
import com.ruoyi.common.utils.sm2.KeyConstant;
import com.ruoyi.common.utils.sm2.SM2Util;
import lombok.SneakyThrows;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
/**
 * 响应加解密拦截器
 *
 * @author 猴哥
 */
//@Component
//@ControllerAdvice
public class ResponseHandler implements ResponseBodyAdvice<Object> {
    /**
     * 返回true，才会走beforeBodyWrite方法
     */
    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        return true;
    }

    /**
     * 响应加密
     */
    @SneakyThrows
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest request, ServerHttpResponse serverHttpResponse) {
        // 拿到响应的数据
        String json = JSON.toJSONString(body);
        // 进行加密
        return SM2Util.encrypt(KeyConstant.PUBLIC_KEY, json);
    }
}
